local M = {}
local config = require("config.apps")
local uiUtils = require("utils.ui")
local eventtap = hs.eventtap
local geometry = hs.geometry

local launcher = {
    grid = nil,
    mouseWatcher = nil,
    mouseMoveWatcher = nil
}

-- 新增：定义颜色常量
local COLORS = {
    normal = {red = 0.2, green = 0.2, blue = 0.2, alpha = 0.9},
    hover = {red = 0.2, green = 0.4, blue = 0.2, alpha = 0.9}  -- 悬停时的绿色
}

-- 创建单个应用单元格
local function createAppCell(x, y, width, height, app)
    local cellFrame = hs.geometry.rect(x, y, width, height)
    local cell = uiUtils.createRoundedBackground(
        x,
        y,
        width,
        height,
        COLORS.normal,
        8
    )

    -- 创建图标
    local iconSize = 50
    local iconPadding = 15
    local iconFrame = hs.geometry.rect(
        x + 20,
        y + (height - iconSize) / 2,
        iconSize,
        iconSize
    )

    local icon = hs.drawing.image(iconFrame, M.getAppIcon(app.name))
    icon:setLevel(hs.drawing.windowLevels.overlay + 2)

    -- 创建文本
    local textHeight = 30
    local textY = y + (height - textHeight) / 2
    local textX = x + 20 + iconSize + iconPadding
    local textFrame = hs.geometry.rect(textX, textY, width - textX + x, textHeight)

    local textStyle = {
        textFont = "SF Pro",
        textSize = 10,
        textColor = {hex = "#FFFFFF"},
        paragraphStyle = {
            alignment = "left",
            lineSpacing = 0,
        },
        padding = {
            left = 0,
            top = 0
        }
    }

    local text = uiUtils.createText(textFrame, string.format("[ %s ] %s", app.id, app.name), textStyle)
    text:setLevel(hs.drawing.windowLevels.overlay + 2)

    return {
        background = cell,
        icon = icon,
        text = text,
        bounds = {x = x, y = y, w = width, h = height, app = app}
    }
end

-- 修改 createAppGrid 函数，添加点击回调参数
local function createAppGrid(callback)
    print("Available apps in config:")
    for i, app in ipairs(config) do
        print(string.format("App %d: name=%s, id=%s, path=%s, bundleID=%s",
            i, app.name, app.id, app.path, app.bundleID))
    end

    local screen = hs.screen.mainScreen()
    local screenFrame = screen:frame()

    local cellWidth = 250
    local cellHeight = 60
    local cellSpacing = 20
    local columnsPerRow = #config >= 3 and 3 or #config

    local gridWidth = (columnsPerRow * cellWidth) + ((columnsPerRow - 1) * cellSpacing)
    local numRows = math.ceil(#config / columnsPerRow)
    local gridHeight = numRows * cellHeight + (numRows - 1) * cellSpacing

    local startX = (screenFrame.w - gridWidth) / 2
    local startY = (screenFrame.h - gridHeight) / 2 + 50

    -- 创建主背景
    local mainBackground = uiUtils.createRoundedBackground(
        startX - 20,
        startY - 100,
        gridWidth + 40,
        gridHeight + 140,
        {red = 0, green = 0, blue = 0, alpha = 0.8},
        20
    )

    -- 创建标题
    local titleFrame = hs.geometry.rect(startX, startY - 80, gridWidth, 60)
    local titleStyle = {
        textFont = "SF Pro",
        textSize = 24,
        textColor = {hex = "#FFFFFF"},
        paragraphStyle = {
            alignment = "left"
        }
    }
    local title = uiUtils.createText(titleFrame, "✨ 应用启动器", titleStyle)
    title:setLevel(hs.drawing.windowLevels.overlay + 1)

    -- 创建所有单元格
    local cells = {}
    for i, app in ipairs(config) do
        local row = math.floor((i-1) / 3)
        local col = (i-1) % 3
        local x = startX + col * (cellWidth + cellSpacing)
        local y = startY + row * (cellHeight + cellSpacing)
        local cell = createAppCell(x, y, cellWidth, cellHeight, app)

        -- 存储单元格的位置信息和应用信息
        cell.bounds = {
            x = x,
            y = y,
            w = cellWidth,
            h = cellHeight,
            app = app
        }

        -- 添加调试信息
        print("Created cell for app:", app.name, "with path:", app.path)

        table.insert(cells, cell)
    end

    return {
        background = mainBackground,
        title = title,
        cells = cells
    }
end

function M.getAppIcon(appName)
    local bundleID = nil
    for _, app in ipairs(config) do
        if app.name == appName then
            bundleID = app.bundleID
            break
        end
    end

    if bundleID then
        local icon = hs.image.imageFromAppBundle(bundleID)
        if icon then
            return icon
        end
    end

    return hs.image.imageFromName(hs.image.systemImageNames.ApplicationIcon)
end

function M.showLauncher(callback)
    if not launcher.grid then
        launcher.grid = createAppGrid(callback)
    end

    -- 创建鼠标移动监听器
    if not launcher.mouseMoveWatcher then
        launcher.mouseMoveWatcher = eventtap.new({eventtap.event.types.mouseMoved}, function(e)
            local mousePoint = geometry.point(e:location())

            -- 遍历所有cell检查鼠标位置
            for _, cell in ipairs(launcher.grid.cells) do
                local bounds = cell.bounds
                local cellRect = geometry.rect(bounds.x, bounds.y, bounds.w, bounds.h)

                if mousePoint:inside(cellRect) then
                    -- 鼠标在当前cell内，设置悬停颜色
                    cell.background:setFillColor(COLORS.hover)
                else
                    -- 鼠标不在当前cell内，恢复正常颜色
                    cell.background:setFillColor(COLORS.normal)
                end
            end

            return false  -- 继续传递事件
        end)
    end

    -- 启动鼠标移动监听器
    launcher.mouseMoveWatcher:start()

    -- 创建鼠标点击监听器
    if not launcher.mouseWatcher then
        print("Creating mouse watcher") -- 调试信息

        -- 检查辅助功能权限
        if not hs.accessibilityState() then
            hs.alert.show("请在系统设置中允许 Hammerspoon 使用辅助功能")
            print("Accessibility not enabled for Hammerspoon")
            return
        end

        launcher.mouseWatcher = eventtap.new({ eventtap.event.types.leftMouseDown }, function(e)
            local mousePoint = geometry.point(e:location())
            print("Mouse clicked at:", mousePoint.x, mousePoint.y)

            -- 获取主背景的边界并打印
            local mainBounds = {
                x = launcher.grid.background:frame().x,
                y = launcher.grid.background:frame().y,
                w = launcher.grid.background:frame().w,
                h = launcher.grid.background:frame().h
            }
            print("Main background bounds:", mainBounds.x, mainBounds.y, mainBounds.w, mainBounds.h)

            -- 检查每个单元格
            for i, cell in ipairs(launcher.grid.cells) do
                local bounds = cell.bounds
                local cellRect = geometry.rect(bounds.x, bounds.y, bounds.w, bounds.h)

                if mousePoint:inside(cellRect) then
                    print("Found matching cell!")
                    print("Cell app data:",
                        "name=", cell.bounds.app.name,
                        "path=", cell.bounds.app.path,
                        "id=", cell.bounds.app.id)

                    if callback then
                        callback(cell.bounds.app)
                    else
                        print("Warning: No callback function provided")
                    end
                end
            end

            -- 无论点击在哪里，都关闭启动器
            M.hideLauncher()
            return true
        end)
    end

    -- 再次检查权限并启动监听器
    if launcher.mouseWatcher then
        local success, err = pcall(function()
            launcher.mouseWatcher:start()
        end)

        if not success then
            print("Failed to start mouse watcher:", err)
            hs.alert.show("启动鼠标监听失败，请检查权限设置")
            return
        end
    end

    launcher.grid.background:show()
    launcher.grid.title:show()
    for _, cell in ipairs(launcher.grid.cells) do
        cell.background:show()
        cell.icon:show()
        cell.text:show()
    end
end

function M.hideLauncher()
    -- 停止鼠标移动监听器
    if launcher.mouseMoveWatcher then
        launcher.mouseMoveWatcher:stop()
    end

    -- 停止鼠标监听器
    if launcher.mouseWatcher then
        launcher.mouseWatcher:stop()
    end

    -- 隐藏界面
    if launcher.grid then
        launcher.grid.background:hide()
        launcher.grid.title:hide()
        for _, cell in ipairs(launcher.grid.cells) do
            cell.background:hide()
            cell.icon:hide()
            cell.text:hide()
        end
    end

    -- 清理所有热键绑定
    local hotkeys = require("modules.app-launcher.hotkeys")
    hotkeys.cleanupHotkeys()
end

return M